import sys
import pygame
from settings import Settings
from ship import Ship
import game_functions as gf
# sprite 类似于列表，但提供了有助于游戏开发的功能
from pygame.sprite import Group
from game_stats import GameStats
from button import Button
from scoreboard import ScoreBoard
from record_history import RecordHistory


def run_game():
    # 初始化游戏，并创建一个屏幕对象
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    # 创建一艘飞船
    ship = Ship(ai_settings, screen)

    # 创建子弹和外星人编组
    bullets = Group()
    aliens = Group()
    gf.create_fleet(ai_settings, screen, ship, aliens)

    # 读取用户历史记录并创建统计信息仪表盘
    stats = GameStats(ai_settings)
    history_record = RecordHistory()
    stats.high_score = history_record.get_high_score()
    score_board = ScoreBoard(ai_settings, screen, stats)

    # 创建 PLay 按钮
    play_button = Button(ai_settings, screen, "Play")

    while True:
        # 事件监测
        gf.check_event(ai_settings, screen, ship, bullets, play_button, stats, aliens, score_board)

        if stats.game_active:
            # 更新飞船 子弹 外星人
            ship.update()
            gf.update_bullets(ai_settings, screen, ship, aliens, bullets, stats, score_board, history_record)
            gf.update_aliens(ai_settings, ship, aliens, stats, screen, bullets, score_board)

        # 刷新屏幕
        gf.update_screen(ai_settings, screen, ship, aliens, bullets, play_button, score_board, stats)


run_game()
